clear all; close all; clc;

R = 100;
 C = 33e-6;
RC = R*C;

Tmod = 10*RC;
T = RC / 1000;

t = 0:T:Tmod;

%% ???????? ?? ???????? ???????????
E  = 0*(t<Tmod/4) + 3*(t>=Tmod/4);

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1); dU(1) = 0;
U2 = U;

for k = 2:length(t)
% ??????? 1 - ??? ?? ????????? ?????????? ??????????? ??????????
    U(k) = U(k-1) + dU(k-1)*T;
    dU(k) = (E(k) - U(k)) / RC;
    
% ??????? 2 - ????????? ?????? ??????????? ?? ???????? ? ??????
    U2(k) = (RC*U2(k-1) + E(k)*T) / (RC + T);
end

figure;
plot(t, E, t, U, t, U2)
xlabel('t, sec');
ylabel('U, V');

%% ????????? ??????????? ??
E  = 7*randn(1, length(t));

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1); dU(1) = 0;

for k = 2:length(t)
    U(k) = U(k-1) + dU(k-1)*T; 
    dU(k) = (E(k) - U(k)) / RC;
end

figure;
plot(t, E, t, U)
xlabel('t, sec');
ylabel('U, V');

%% ??????????? ?????????
f = 10; % Hz
A = 1;
E  = A*sin(2*pi*f*t);

U = nan(1, length(t));
dU = nan(1, length(t));

U(1) = E(1); dU(1) = 0;

for k = 2:length(t)
    U(k) = U(k-1) + dU(k-1)*T;
    dU(k) = (E(k) - U(k)) / RC;
end

figure;
plot(t, E, t, U)
xlabel('t, sec');
ylabel('U, V');

%% ???

fmin = 1/ (Tmod/2);
fmax = 1/T / 2;
f = fmin:((fmax-fmin)/100):fmax;
A = 1;
K = nan(1, length(f));
for j = 1:length(f)
    E  = A*sin(2*pi*f(j)*t);
    
    U = nan(1, length(t));
    dU = nan(1, length(t));
    
    U(1) = E(1); dU(1) = 0;
    
    for k = 2:length(t)
        U(k) = U(k-1) + dU(k-1)*T;
        dU(k) = (E(k) - U(k)) / RC;
    end
    
    Us = U(fix(end/2):end);
    K(j) = (max(Us) - min(Us)) / 2;
end

figure;
plot(f, K)
xlabel('f, Hz');
ylabel('K');

%% ??? - ???????????? ??????? ?????????????
Tmod = 1000*RC;
T = RC / 100;
t = 0:T:Tmod;

fmin = 1/ (Tmod/2);
fmax = 2 *  (1/ RC /  2 / pi);
f = fmin:((fmax-fmin)/100):fmax;
A = 1;
K = nan(1, length(f));
for j = 1:length(f)
    E  = A*sin(2*pi*f(j)*t);
    
    U = nan(1, length(t));
    dU = nan(1, length(t));
    
    U(1) = E(1); dU(1) = 0;
    
    for k = 2:length(t)
        U(k) = U(k-1) + dU(k-1)*T;
        dU(k) = (E(k) - U(k)) / RC;
    end
    
    Us = U(fix(end/2):end);
    K(j) = (max(Us) - min(Us)) / 2;
end

figure;
plot(f, 20*log10(K))
xlabel('f, Hz');
ylabel('K, dB');
grid on